﻿using Google.GData.Client;
using System;
using System.Collections.ObjectModel;

namespace Desktop.Library
{
    public class Blog : ObservableCollection<AtomEntry>
    {
        #region Constructors

        public Blog(Service service, AtomEntry entry, string feedUrl)
        {
            Service = service;
            Entry = entry;
            FeedUrl = feedUrl;

            Refresh();
        }

        #endregion

        #region Properties

        public AtomEntry Entry { get; private set; }

        private string FeedUrl { get; set; }
        private Service Service { get; set; }

        #endregion

        #region Methods

        public void Refresh()
        {
            if (string.IsNullOrEmpty(FeedUrl))
            {
                return;
            }

            FeedQuery query = new FeedQuery(FeedUrl);

            Clear();
            AtomFeed feed = Service.Query(query);
            while ((feed != null) && (feed.Entries.Count > 0))
            {
                foreach (AtomEntry entry in feed.Entries)
                {
                    Add(entry);
                }

                // Do the chunking:
                if (feed.NextChunk != null)
                {
                    query.Uri = new Uri(feed.NextChunk);
                    feed = Service.Query(query);
                }
                else
                {
                    feed = null;
                }
            }
        }

        public AtomEntry InsertEntry(AtomEntry entry)
        {
            if (entry == null)
            {
                return null;
            }
            entry = Service.Insert(new Uri(FeedUrl), entry);
            Refresh();
            return entry;
        }

        public AtomEntry UpdateEntry(AtomEntry entry)
        {
            if (entry == null)
            {
                return null;
            }
            if (!Contains(entry))
            {
                throw new Exception("The input entry is not a part of this blog.");
            }
            entry = Service.Update(entry);
            Refresh();
            return entry;
        }

        public void DeleteEntry(AtomEntry entry)
        {
            if (entry == null)
            {
                return;
            }
            if (!Contains(entry))
            {
                throw new Exception("The input entry is not a part of this blog.");
            }
            Service.Delete(entry);
            Refresh();
        }

        #endregion
    }
}
